﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Data;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Linq;
using Utilities;
using System.Configuration;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using System.Diagnostics;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.ServiceModel;

namespace WMI
{
    class Program
    {
        public static object GetItemsFromMOArray(object MOSObject)
        {
            string items = string.Empty;
            foreach (string item in MOSObject as string[])
            {
                items += item + " , ";
            }
            return items;
        }

        static void Main(string[] args)
        {
                WebServiceHost host = new WebServiceHost(typeof(WMIService.Service), new Uri(ConfigurationManager.AppSettings["endPoint"]));
                ServiceEndpoint sep = host.AddServiceEndpoint(typeof(WMIService.IService), new WebHttpBinding(), "");
                ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
                sdb.IncludeExceptionDetailInFaults = true;
                sdb.HttpHelpPageEnabled = true;
                host.Open();
                Console.ReadKey();


            //RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Mynte");
            //Console.Write(reg.GetValue("InstallationFolder").ToString());
            //WMI.Classes.GetAllClasses();
            //Utilities.Reader r = new Reader();
            //WMI.Classes.GetClassesByScheduling();
            //WMI.Classes.GetAllClasses();
            ////StreamReader reader = new StreamReader(WebRequest.Create("http://127.0.0.1:2703/GetAllClasses").GetResponse().GetResponseStream());
            //WMI.Classes.DiskDrive();
            //string s = WMI.Classes.LocalWMI.GetXml();
            //s = Regex.Replace(s, "[\x01-\x1F]","");
            //Console.Write(s);
            //WMI.Classes.GetAllClasses();
            //DataSet ds = WMI.Classes.LocalWMI;
            //String InsertQuery = string.Empty;

            //foreach (DataTable Table in ds.Tables)
            //{
            //    foreach (DataRow Row in Table.Rows)
            //    {
            //        InsertQuery += String.Format("INSERT INTO {0} VALUES (", Table.TableName);
            //        for (int i = 0; i < Table.Columns.Count; i++)
            //        {
            //            InsertQuery += String.Format("'{0}', ", Row[i].ToString().Replace('\'', ' ').Replace("(", " ").Replace(")", " "));
            //        }
            //        InsertQuery = InsertQuery.Remove(InsertQuery.Length - 2);
            //        InsertQuery += ");\r\n";
            //    }
            //}

            //try
            //{
            //    using (SQLiteConnection conn = new SQLiteConnection(Environment.ExpandEnvironmentVariables(ConfigurationManager.ConnectionStrings["SQLite"].ConnectionString)))
            //    {
            //        conn.Open();
            //        using (SQLiteCommand comm = new SQLiteCommand(conn))
            //        {
            //            foreach (string query in InsertQuery.Split(new string[] { "\r\n" }, StringSplitOptions.None))
            //            {
            //                comm.CommandText = query;
            //                comm.ExecuteNonQuery();
            //            }
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}


            //Console.ReadKey();
            //Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //ConfigurationSectionGroup grp = cfg.GetSectionGroup("Scheduling");
            //ClassSection cs = grp.Sections["class"] as ClassSection;

            //WMI.Classes.GetAllClasses();
            //DataSet ds = Classes.LocalWMI;
            //BinaryFormatter bf = new BinaryFormatter();
            //FileStream fs = new FileStream(Environment.ExpandEnvironmentVariables("%allusersprofile%//DataSet.bin"), FileMode.Create);
            //ds.RemotingFormat = SerializationFormat.Binary;
            //bf.Serialize(fs, ds);


            //WMI.Classes.GetAllClasses();
            //Utilities.SQLite.CreateTables(WMI.Classes.LocalWMI);
            //Utilities.SQLite.InsertData(WMI.Classes.LocalWMI);

            //WMI.Classes.GetClassesByScheduling();

            //Utilities.Reader r = new Reader();
            //r.UpdateData("Win32_BaseBoard");

            //Utils.SQLite.InsertData(ds);
            //int table = 23;
            //bool flag = true;
            //while (flag)
            //{
            //    if (WMI.Classes.LocalWMI.Tables.Count == table)
            //    {
            //        flag = false;
            //        Utils.SQLite.CreateTables(WMI.Classes.LocalWMI);
            //    }
            //}

            //string schema = ds.GetXmlSchema();
            
            //Print(ds);
            //Write(ds);5
            //WMI.Classes.GetAllClasses();
            //WindowsService.SQLite.CreateTables(WMI.Classes.LocalWMI);
            //WindowsService.SQLite.InsertData(WMI.Classes.LocalWMI);
            //WMI.Classes.GetByQuery(@"Select * FROM Win32_Service ");
            //%allusersprofile%\\sqlite.exe WMIService.db .dump > %allusersprofile%\\dump

            //WMI.Classes.BaseBoard();
            //string SQLitePath = Environment.ExpandEnvironmentVariables("%ProgramFiles%") + "\\sqlite.exe";
            //Environment.SetEnvironmentVariable("PATH", Environment.ExpandEnvironmentVariables("PATH") + Environment.ExpandEnvironmentVariables("%ProgramFiles%"));
            //System.Diagnostics.Process SQLite = new System.Diagnostics.Process();
            //SQLite.StartInfo.LoadUserProfile = true;
            //SQLite.StartInfo.FileName = "cmd.exe";
            //SQLite.StartInfo.Arguments = "/c  sqlite .\\WMIService\\WMIService.db .dump > .\\WMIService\\WMIService.dump";
            //SQLite.StartInfo.WorkingDirectory = Environment.ExpandEnvironmentVariables("%ProgramFiles%");
            //if(!File.Exists(SQLitePath))
            //    File.WriteAllBytes(SQLitePath, WindowsService.Properties.Resources.sqlite);
            //SQLite.Start();
            //DataSet ds = new DataSet();
            //string cmdText = System.IO.File.ReadAllText(Environment.ExpandEnvironmentVariables("%allusersprofile%/dump.sql"));
            //try
            //{
                
            //}

            //catch (Exception ex)
            //{

            //}
            Console.ReadKey();
        }

        /// <summary>
        /// Stampa tutto il contenuto del dataset
        /// </summary>
        static void Print(DataSet ds)
        {
            string debug = "VideoController";
            int i = 0;
            foreach (DataTable table in ds.Tables)
            {
                if ((debug == table.ToString()) || (debug == "all"))
                {
                    Console.Write(table.ToString() + "\n\n");
                    foreach (DataRow row in table.Rows)
                    {
                        foreach (Object s in row.ItemArray)
                        {
                            Console.Write(row.Table.Columns[i] + "   " + s.ToString() + "\n");
                            i++;
                        }
                        Console.Write("\n");

                        i = 0;
                    }
                }
            }
            Console.ReadKey();
        }

        /// <summary>
        /// Crea un file di log (output.log)
        /// </summary>
        static void Write(DataSet ds)
        {
            StreamWriter swf = new StreamWriter("output.log");
            int i = 0;
            foreach (DataTable table in ds.Tables)
            {
                
                    swf.WriteLine(table.ToString());
                    foreach (DataRow row in table.Rows)
                    {
                        foreach (Object s in row.ItemArray)
                        {
                            swf.WriteLine(row.Table.Columns[i] + "   " + s.ToString());
                            i++;
                        }
                        swf.WriteLine();

                        i = 0;
                    }
                
            }
        }


    }
}
